<template>
  <div style="font-size:15px;font-weight: 600;margin-left: 60px;">查看产品</div>
    <div class="reject" v-if="state.dataForm.audit === 2">
        <span>驳回原因：
            <a  style="color: red;font-weight: 400;">{{state.dataForm.auditRemark}}</a>
        </span>
    </div>
  <div>
    <el-tabs v-model="activeTab" style="margin-left: 60px;margin-top: 20px;">
      <el-tab-pane label="基础信息" name="tab1">
        <el-form label-width="110px" style="margin-top: 20px;margin-left: -32px;" :model="state.dataForm"
          ref="dataFormRef">
          <el-row>
            <el-col>
              <el-form-item label="系列名称" prop="seriesName">
                <el-text>{{ state.dataForm.seriesName }}系列</el-text>
              </el-form-item>
            </el-col>
            <el-col>
              <el-form-item label="产品分类" prop="class3Id">
                <el-text>{{ state.dataForm.className }}</el-text>
              </el-form-item>
            </el-col>
            <el-col>
              <el-form-item label="产品品牌" prop="brandId">
                <el-text>{{ state.dataForm.brandName }}</el-text>
              </el-form-item>
            </el-col>
            <el-col>
              <el-form-item label="产品主图" prop="mainImages">
                <div class="upload-box">
                  <img v-if="!state.dataForm.mainImages" src="../../assets/images/upload.png" alt="相机图标" class="icon" />
                  <el-image v-else :src="state.dataForm.mainImages" :preview-src-list="[state.dataForm.mainImages]"
                    fit="cover" class="uploaded-image" />
                </div>
              </el-form-item>
            </el-col>
            <el-col>
              <el-form-item label="产品详情" prop="name">
                <div class="image-upload-container">
                  <div class="upload-tip">
                    <div class="tip-text">最多可上传10张，已上传 {{ uploadedFiles.length }}/10</div>
                  </div>
                  <div style="display: flex;flex-wrap: wrap;">
                    <div class="upload-box" v-if="!state.dataForm.imgUrls">
                      <img src="../../assets/images/upload.png" alt="" class="icon" />
                    </div>
                    <div v-else style="display: flex; flex-wrap: wrap;">
                      <div v-for="(item, index) in uploadedFiles || []" :key="index" style="margin-right: 20px;">
                        <el-image :src="item" :preview-src-list="uploadedFiles || []" fit="cover"
                          class="uploaded-image" />
                      </div>
                    </div>
                  </div>
                </div>
              </el-form-item>
            </el-col>
            <el-col>
              <el-form-item>
                <el-button type="primary" @click="showPreview = true">页面预览</el-button>
                <el-image-viewer v-if="showPreview" :url-list="srcList" show-progress :initial-index="4"
                  @close="showPreview = false" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </el-tab-pane>
      <el-tab-pane label="型号信息" name="tab2">
        <el-form style="margin-top: 20px;" :model="state.dataForm" ref="dataFormRef">
          <div class="model">
            <el-tabs v-model="editableTabsValue" type="card" class="demo-tabs" closable>
              <el-tab-pane v-for="(item, index) in editableTabs" :key="item.name" :label="item.productName"
                :name="item.name">
                <!-- 图片/视频上传区域（每个tab独立文件列表） -->
                <div style="color: rgba(56, 56, 56, 1);margin-bottom: 15px;font-size: 13px;">产品图片/视频</div>
                <el-form-item prop="name">
                  <div class="image-upload-container" style="width: 684px;">
                    <div class="upload-tip">
                      <div style=" color:rgba(56, 56, 56, 1);">产品图片/视频上传</div>
                      仅支持上传图片、视频，最多可上传6张与1个视频，
                      已上传 {{ item.banarImg!.split(',').length }}/6图片、{{ (item.productVideoUrl ? 1 : 0) }}/1视频，拖拽图片可调整顺序
                    </div>
                    <!-- 图片上传组件（绑定当前tab的imageFiles） -->
                    <div class="image-upload-section">
                      <div class="image-upload-label">图片：</div>
                      <div class="upload-box" v-if="!item.banarImg || item.banarImg === ''">
                        <img src="../../assets/images/upload.png" alt="相机图标" class="icon" />
                      </div>
                      <div v-else style="display: flex;flex-wrap: wrap;">
                        <div v-for="(imgUrl, index) in item.banarImg.split(',')" :key="index" class="upload-box"
                          style="margin-right: 20px;">
                          <el-image :src="imgUrl" :preview-src-list="item.banarImg.split(',')" fit="cover"
                            class="uploaded-image" />
                        </div>
                      </div>
                    </div>
                    <!-- 视频上传组件（绑定当前tab的videoFiles） -->
                    <div class="video-upload-section" v-if="item.productVideoUrl">
                      <div class="video-upload-label">视频：</div>
                      <div v-if="!item.productVideoUrl">
                        <el-icon>
                          <VideoCamera />
                        </el-icon>
                      </div>
                      <div class="upload-box" v-else>
                        <video :src="item.productVideoUrl" class="uploaded-image" controls></video>
                      </div>
                    </div>
                  </div>
                </el-form-item>
                <el-form-item label="参数信息" prop="name" style="font-weight: 600;"></el-form-item>

                <!-- 属性组示例（假设每个tab有独立的属性组数据） -->
                <div v-for="(group, groupIndex) in item.productAttrGroupList" :key="groupIndex"
                  style="display: flex; align-items: center;">
                  <div class="attribute-group">
                    <div style="font-size: 14px; font-weight: 600;margin-bottom: 30px;">{{ group.groupName }}</div>
                    <el-form-item v-for="(itemInput, inputIndex) in group.productAttrs" :key="inputIndex"
                      style="margin-bottom: 20px;">
                      <div style="width: 96px;">{{ itemInput.attrName }}</div>
                      <el-text>{{ itemInput.attrValue }}</el-text>
                    </el-form-item>
                  </div>
                </div>
              </el-tab-pane>
            </el-tabs>
          </div>
        </el-form>
      </el-tab-pane>
      <el-tab-pane label="供应商信息" name="tab3">
        <el-form :inline="true" :model="state.dataForm" style="margin-top: 10px;">
          <el-table :header-cell-style="{ 'background': '#eef1f6', 'color': '#1f2d3d', 'border-color': '#dfe6ec' }"
            v-loading="state.dataListLoading" :data="state.dataList" border
            @selection-change="state.dataListSelectionChangeHandle" style="width: 100%">
            <el-table-column align="center" prop="company" label="供应商名称" width="200"
              show-overflow-tooltip></el-table-column>
            <el-table-column align="center" prop="serviceArea" label="服务区域" show-overflow-tooltip></el-table-column>
            <el-table-column align="center" prop="productName" label="型号信息" width="280"
              show-overflow-tooltip></el-table-column>
            <el-table-column align="center" prop="quotation" label="报价" width="200"
              show-overflow-tooltip></el-table-column>
            <el-table-column align="center" prop="effectiveDate" label="报价日期" width="280"
              show-overflow-tooltip></el-table-column>
            <el-table-column align="center" prop="status" label="状态" width="200">
              <template #default="scope">
                <el-tag v-if="scope.row.status == 0" type="success">生效</el-tag>
                <el-tag v-else-if="scope.row.status == 1" type="danger">失效</el-tag>
              </template>
            </el-table-column>
          </el-table>
        </el-form>
        <el-pagination :current-page="state.page" :page-sizes="[10, 20, 50, 100]" :page-size="state.limit"
          :total="state.total" layout="total, sizes, prev, pager, next, jumper"
          @size-change="state.pageSizeChangeHandle" @current-change="state.pageCurrentChangeHandle"> </el-pagination>
      </el-tab-pane>
    </el-tabs>
  </div>
   <!-- 审核 -->
    <add-or-update :key="addKey" ref="addOrUpdateRef" @refreshDataList="refreshDataList" @auditSuccess="onAuditSuccess"></add-or-update>
  <div class="foot">
        <el-button class="quxiao" @click="cancel()">{{ $t("cancel") }}</el-button>
        <el-button type="primary" @click="addOrUpdateHandle(state.dataForm.id)">审核</el-button>
    </div>
</template>

<script lang="ts" setup>
import baseService from "@/service/baseService";
import { ElMessage } from "element-plus";
import { useRoute, useRouter } from 'vue-router';
import useView from "@/hooks/useView";
import { reactive, ref, toRefs, onMounted, computed, nextTick } from "vue";
import { useI18n } from "vue-i18n";
import AddOrUpdate from "./nocproduct-audit.vue";

const { t } = useI18n();

const router = useRouter();
const route = useRoute();
const id = route.query.id;

const dataFormRef = ref();
const view = reactive({
  getDataListURL: '/noc/productuserquotation/queryPageForSeries',
  getDataListIsPage: true,
  dataForm: {
    seriesId: id,
    seriesName: "",
    className: "",
    brandName: "",
    mainImages: "",
    imgUrls: "", // 改为字符串类型，存储逗号分隔的URL
    productList: [] as Product[],
    audit:"",
    auditRemark:""
  }
});

// 审核成功后关闭当前页并返回列表
const onAuditSuccess = () => {
  state.closeCurrentTab(); // 关闭当前标签页
  router.push('/program/nocproduct-list'); // 返回列表页
};
const state = reactive({ ...useView(view), ...toRefs(view) });

const uploadedFiles = ref<string[]>([]);

// tab切换显示
const activeTab = ref('tab1');

const init = () => {
  // 重置表单数据
  if (dataFormRef.value) {
    dataFormRef.value.resetFields();
  }

  if (id) {
    baseService.get("/noc/productseries/info/" + id).then((res) => {
      if (res.code === 0 && res.data) {
        Object.assign(state.dataForm, res.data);
        console.log(state.dataForm);
        // 如果有已上传的图片，初始化uploadedFiles
        if (state.dataForm.imgUrls) {
          uploadedFiles.value = state.dataForm.imgUrls.split(',');
        }
        // 确保 productAttrGroupList 是一个数组
        const productList = Array.isArray(res.data.productList) ? res.data.productList : [];
        console.log(productList);
        editableTabs.value = productList.map((product: any) => {
          console.log(product);
          // 确保 banarImg 是字符串，否则设为空数组
          // 确保 productAttrGroupList 是一个数组
          const attrGroupList = Array.isArray(product.productAttrGroupList) ? product.productAttrGroupList : [];
          return {
            id: product.id,
            seriesId: product.seriesId,
            productName: product.productName,
            name: product.productName,
            banarImg: product.banarImg,
            productVideoUrl: product.productVideoUrl,
            productAttrGroupList: attrGroupList.map((productAttrGroup: any) => {
              // 确保 productAttrs 是一个数组
              const attrs = Array.isArray(productAttrGroup.productAttrs) ? productAttrGroup.productAttrs : [];
              return {
                id: productAttrGroup.id,
                productId: productAttrGroup.productId,
                groupId: productAttrGroup.groupId,
                seriesId: productAttrGroup.seriesId,
                groupName: productAttrGroup.groupName,
                productAttrs: attrs.map((productAttr: any) => ({
                  id: productAttr.id,
                  productId: productAttr.productId,
                  attrId: productAttr.attrId,
                  productAttrGroupId: productAttr.productAttrGroupId,
                  attrName: productAttr.attrName,
                  attrValue: productAttr.attrValue
                }))
              };
            })
          };
        });
        // 如果存在型号数据，默认选中第一个
        console.log(editableTabs.value);
        if (editableTabs.value && editableTabs.value.length > 0) {
          editableTabsValue.value = editableTabs.value[0].name;
        }
      } else {
        ElMessage.error('获取产品系列信息失败');
      }
    });
  }
};

// 可编辑标签页数据结构（每个tab独立存储图片/视频列表和属性组）

interface Product {
  id: number;
  name: string;
  productName: string;
  banarImg: string;
  productVideoUrl: string;
  productAttrGroupList: {
    id: number;
    groupName: string;
    productAttrs: {
      id: number;
      attrName: string;
      attrValue: string
    }[]
  }[];
}

const editableTabs = ref<Product[]>([]); // 响应式tab列表
const editableTabsValue = ref<string>(''); // 当前激活的tab名称
let tabIndex = 0; // 用于生成唯一标识

// 图片输入框引用，指定类型并初始化为null
const imageInput = ref<HTMLInputElement | null>(null);

onMounted(() => {
  const inputElement = document.querySelector('input[type="file"]');
  if (inputElement) {
    try {
      imageInput.value = inputElement as HTMLInputElement;
    } catch (error) {
      console.error("获取input元素时出错:", error);
    }
  }
});

// 保留handleChange函数用于其他地方可能的引用

const showPreview = ref(false);

// 页面预览
const srcList = computed(() => {
  // 如果有上传的图片，则使用上传的图片URL进行预览
  if (state.dataForm.imgUrls && state.dataForm.imgUrls.length > 0) {
    return state.dataForm.imgUrls.split(',');
  }
  // 否则返回默认图片列表
  return [
    'https://fuss10.elemecdn.com/a/3f/3302e58f9a181d2509f3dc0fa68b0jpeg.jpeg',
    'https://fuss10.elemecdn.com/1/34/19aa98b1fcb2781c4fba33d850549jpeg.jpeg',
    'https://fuss10.elemecdn.com/0/6f/e35ff375812e6b0020b6b4e8f9583jpeg.jpeg',
    'https://fuss10.elemecdn.com/9/bb/e27858e973f5d7d3904835f46abbdjpeg.jpeg',
    'https://fuss10.elemecdn.com/d/e6/c4d93a3805b3ce3f323f7974e6f78jpeg.jpeg',
    'https://fuss10.elemecdn.com/3/28/bbf893f792f03a54408b3b7a7ebf0jpeg.jpeg',
    'https://fuss10.elemecdn.com/2/11/6535bcfb26e4c79b48ddde44f4b6fjpeg.jpeg'
  ];
});

const cancel = () => {
  router.push('/program/nocproduct-list');
  // 关闭当前标签页（需确保useView hook已正确配置）
  state.closeCurrentTab();
};

//刷新数据
const refreshDataList = () => {
    state.refreshDataList();
};

//审核
const addKey = ref(0);
const addOrUpdateRef = ref();
const addOrUpdateHandle = (id?: number | string) => {
    addKey.value++;
    nextTick(() => {
        addOrUpdateRef.value.init(id);
    });
};

// 页面进入执行
init();
</script>

<style lang="scss" scoped>
.el-input {
  width: 224px;
  height: 32px;
  opacity: 1;
  border-radius: 5px;
  background: rgba(255, 255, 255, 1);
}

.el-select {
  width: 224px;
  height: 32px;
  opacity: 1;
  border-radius: 5px;
  background: rgba(255, 255, 255, 1);
}

.form {
  display: flex;
  justify-content: space-between;
}

.image-upload-container {
  width: 511px;
  border: 1px dashed #ccc;
  border-radius: 6px;
  padding: 10px;
}

.upload-tip {
  font-size: 13px;
  color: rgba(168, 171, 178, 1);
  margin-bottom: 10px;
}

.tip-text {
  color: #999;
  font-size: 14px;
}

.upload-dragger {
  width: 100%;
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}


.upload-over-tip {
  color: #999;
  text-align: center;
}

.quxiao {
  border-radius: 5px;
  background: rgba(239, 244, 255, 1);
  color: rgba(22, 119, 255, 1);
  border: 1px solid rgba(22, 119, 255, 1);
}

.foot {
  display: flex;
  justify-content: end;
  position: absolute;
  bottom: 50px;
  right: 50px;
}

.add-button {
  width: 100px;
  height: 32px;
  padding: 10px 20px;
  background-color: rgba(22, 119, 255, 1);
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  margin-bottom: 20px;
}

.add-button:hover {
  background-color: rgba(22, 119, 255, 1);
}

.model-container {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  justify-content: center;
}

.model-item {
  display: flex;
  align-items: center;
}

.model-select {
  padding: 8px;
  margin-right: 10px;
  border: 1px solid #ccc;
  border-radius: 4px;
}

.model-input {
  padding: 8px;
  margin-right: 10px;
  border-radius: 5px;
  width: 156px;
  height: 32px;
  background: rgba(255, 255, 255, 1);
  border: 1px solid rgba(199, 199, 199, 1);
}

.model-input:focus {
  border: 0px;
  /* 获得焦点时边框颜色改为蓝色 */
  background: rgba(240, 245, 255, 1);
  color: rgba(22, 119, 255, 1);
  outline: none;
  /* 去除默认的焦点轮廓 */
}

.remove-button {
  padding: 8px 12px;
  background-color: #f44336;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.uploaded-image {
  width: 120px;
  height: 120px;
  object-fit: cover;
}

.brand-upload {
  display: block;
}

.upload-box {
  width: 100px;
  height: 100px;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  display: flex;
  justify-content: center;
  align-items: center;
  transition: border-color 0.3s;
}

.upload-box:hover {
  border-color: #409EFF;
}

.upload-box .icon {
  width: 32px;
  height: 32px;
}



// 产品图片/视频
.image-upload-section {
  display: flex;
  margin-bottom: 20px;
}

.image-upload-label {
  width: 50px;
}

.video-upload-section {
  display: flex;
}

.video-upload-label {
  width: 50px;
}

:deep(.el-upload--picture-card) {
  // background-repeat: no-repeat;
  // background-image: url(../../assets/images/upload.png);
  width: 80px !important;
  height: 80px !important;
}

.attribute-group {
  width: 684px;
  height: 100%;
  padding: 20px;
  border: 1px dashed rgba(31, 31, 31, 0.36);
  border-radius: 18px;
  margin-bottom: 38px;

}

.attribute-group-input {
  width: 492px;
  height: 32px;
}
.reject{
    margin-top: 20px;
    margin-left: 60px;
    height: 92px;
    border-radius: 6px;
    background-color: rgba(255,255,255,1);
    border: 1px solid rgba(187,187,187,1);
}
.reject span{
    font-weight: 600;
    margin-left: 30px;
    line-height: 92px;
    font-size: 16px;
}

</style>
